package org.jeecg.modules.bobo.common.aspect;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.fasterxml.jackson.annotation.JsonFormat;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.jeecg.common.api.CommonAPI;
import org.jeecg.common.aspect.annotation.Dict;
import org.jeecg.common.constant.CommonConstant;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.bobo.common.aspect.annotation.LbAbsFileUrl;
import org.jeecg.modules.bobo.common.aspect.annotation.LbImgBase64;
import org.jeecg.modules.bobo.common.util.ImgUtils;
import org.jeecg.modules.bobo.common.util.IpUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Field;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * @Description: 字典aop类
 * @Author: dangzhenghui
 * @Date: 2019-3-17 21:50
 * @Version: 1.0
 */
@Aspect
@Component
@Slf4j
public class LbDictAspect {
    private HttpServletRequest request;
    @Value(value = "${jeecg.path.upload}")
    private String uploadpath;
    @Autowired
    private CommonAPI commonAPI;
    // 定义切点Pointcut
    @Pointcut("@within(org.jeecg.modules.bobo.common.aspect.annotation.LbAutoDict)")
    public void excudeService() {
    }

    @Pointcut("@annotation(org.jeecg.modules.bobo.common.aspect.annotation.NoLbAutoDict)")
    public void serviceMethods2() {
    }

    @Pointcut("excudeService() && !serviceMethods2()")
    public void serviceMethods3() {
    }





    @Around("serviceMethods3()")
    public Object doAround(ProceedingJoinPoint pjp) throws Throwable {
        //获取RequestAttributes
        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
        //从获取RequestAttributes中获取HttpServletRequest的信息
        request = (HttpServletRequest) (requestAttributes != null ? requestAttributes.resolveReference(RequestAttributes.REFERENCE_REQUEST) : null);
        long time1=System.currentTimeMillis();
        Object result = pjp.proceed();
        long time2=System.currentTimeMillis();
        log.debug("获取JSON数据 耗时："+(time2-time1)+"ms");
        long start=System.currentTimeMillis();
        this.parseDictText(result);
        long end=System.currentTimeMillis();
        log.debug("解析注入JSON数据  耗时"+(end-start)+"ms");
        return result;
    }

    /**
     * 本方法针对返回对象为Result 的IPage的分页列表数据进行动态字典注入
     * 字典注入实现 通过对实体类添加注解@dict 来标识需要的字典内容,字典分为单字典code即可 ，table字典 code table text配合使用与原来jeecg的用法相同
     * 示例为SysUser   字段为sex 添加了注解@LbDict(dictCode = "sex") 会在字典服务立马查出来对应的text 然后在请求list的时候将这个字典text，已字段名称加_dictText形式返回到前端
     * 例输入当前返回值的就会多出一个sex_dictText字段
     * {
     *      sex:1,
     *      sex_dictText:"男"
     * }
     * 前端直接取值sext_dictText在table里面无需再进行前端的字典转换了
     *  customRender:function (text) {
     *               if(text==1){
     *                 return "男";
     *               }else if(text==2){
     *                 return "女";
     *               }else{
     *                 return text;
     *               }
     *             }
     *             目前vue是这么进行字典渲染到table上的多了就很麻烦了 这个直接在服务端渲染完成前端可以直接用
     * @param result
     */
    private void parseDictText(Object result) {
        if (result instanceof org.jeecg.modules.bobo.common.util.Result) {
            List<JSONObject> items = new ArrayList<>();
            Object data = ((org.jeecg.modules.bobo.common.util.Result) result).getData();
            if (data instanceof IPage) {
                List records = ((IPage) data).getRecords();
                if (records.size()>0){
                    if (records.get(0)!=null && !(records.get(0) instanceof String) && !records.get(0).getClass().isPrimitive()){
                        setDictText(items, records);
                        ((IPage) data).setRecords(items);
                    }
                }



            }else if (data instanceof List){
                List records = (List) data;
                if (records.size()>0) {
                    if (records.get(0) != null && !(records.get(0) instanceof String) && !records.get(0).getClass().isPrimitive()) {
                        setDictText(items, records);
                        ((org.jeecg.modules.bobo.common.util.Result) result).setData(items);
                    }
                }

            }else if (data instanceof Map){
//                循环map
//                ((Result) result).setData(setOneDictText(data));
            }
            else if (data !=null && !(data instanceof String) && !data.getClass().isPrimitive()){
                ((org.jeecg.modules.bobo.common.util.Result) result).setData(setOneDictText(data));
            }

        }else if (result instanceof org.jeecg.common.api.vo.Result){
            List<JSONObject> items = new ArrayList<>();
            Object result1 = ((org.jeecg.common.api.vo.Result) result).getResult();
            if (result1 instanceof IPage) {
                List records = ((IPage) ((org.jeecg.common.api.vo.Result) result).getResult()).getRecords();
                setDictText(items, records);
                ((IPage) ((org.jeecg.common.api.vo.Result) result).getResult()).setRecords(items);
            }else if (((org.jeecg.common.api.vo.Result) result).getResult() instanceof List){
                setDictText(items, (List) ((org.jeecg.common.api.vo.Result) result).getResult());
                ((org.jeecg.common.api.vo.Result) result).setResult(items);
            }
            else if (result1 instanceof Map){

            }else if (result1!=null && !(result1 instanceof String) && !result1.getClass().isPrimitive()){
                ((org.jeecg.common.api.vo.Result) result).setResult(setOneDictText(result1));
            }
        }
    }

    private JSONObject setOneDictText(Object object) {
        ObjectMapper mapper = new ObjectMapper();
        String json="{}";
        try {
            //解决@JsonFormat注解解析不了的问题详见SysAnnouncement类的@JsonFormat
            json = mapper.writeValueAsString(object);
        } catch (JsonProcessingException e) {
            log.error("json解析失败"+e.getMessage(),e);
        }
        JSONObject item = JSONObject.parseObject(json);
        //update-begin--Author:scott -- Date:20190603 ----for：解决继承实体字段无法翻译问题------
        //for (Field field : record.getClass().getDeclaredFields()) {
        for (Field field : oConvertUtils.getAllFields(object)) {
            //update-end--Author:scott  -- Date:20190603 ----for：解决继承实体字段无法翻译问题------

            if (field.getAnnotation(Dict.class) != null) {
                String code = field.getAnnotation(Dict.class).dicCode();
                String text = field.getAnnotation(Dict.class).dicText();
                String table = field.getAnnotation(Dict.class).dictTable();
                String key = String.valueOf(item.get(field.getName()));
                //翻译字典值对应的txt
                String textValue = translateDictValue(code, text, table, key);

                log.debug(" 字典Val : "+ textValue);
                log.debug(" __翻译字典字段__ "+field.getName() + CommonConstant.DICT_TEXT_SUFFIX+"： "+ textValue);
                item.put(field.getName() + CommonConstant.DICT_TEXT_SUFFIX, textValue);
            }
            if (field.getAnnotation(LbImgBase64.class) != null) {
                LbImgBase64 type = field.getAnnotation(LbImgBase64.class);
                Object imgval = item.get(field.getName());
                //翻译字典值对应的txt
                String base64 = setBase64(imgval,type);
                item.put(field.getName() + "_base64", base64);
            }
            if (field.getAnnotation(LbAbsFileUrl.class) != null) {

                LbAbsFileUrl type = field.getAnnotation(LbAbsFileUrl.class);
                Object imgval = item.get(field.getName());
                //转换图片为base64
                String absurl = setAbsUrl(imgval,type);
                item.put(field.getName() + "_absurl", absurl);
            }

            //date类型默认转换string格式化日期
            if (field.getType().getName().equals("java.util.Date")&&field.getAnnotation(JsonFormat.class)==null&&item.get(field.getName())!=null){
                SimpleDateFormat aDate=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                item.put(field.getName(), aDate.format(new Date((Long) item.get(field.getName()))));
            }
        }
        return item;
    }

    private String setBase64(Object imgval, LbImgBase64 type) {
        if (type.type().equals("1")){
            if(oConvertUtils.isEmpty(imgval)) {
                return null;
            }
            return ImgUtils.ImageToBase64ByLocal(uploadpath,String.valueOf(imgval));
        }else if (type.type().equals("2")){
            if(oConvertUtils.isEmpty(imgval)) {
                return null;
            }
            StringBuffer textValue=new StringBuffer();
            String[] keys = String.valueOf(imgval).split(",");
            for (String k : keys) {
                String tmpValue = null;
                if (k.trim().length() == 0) {
                    continue; //跳过循环
                }
                tmpValue= ImgUtils.ImageToBase64ByLocal(uploadpath,k);
                if (tmpValue != null) {
                    if (!"".equals(textValue.toString())) {
                        textValue.append(",.,");
                    }
                    textValue.append(tmpValue);
                }
            }
            return textValue.toString();
        }
//        else if (type.type().equals("3")){
//            List<JSONObject> items = new ArrayList<>();
//            Class<T> tClass = type.className();
//
//            setDictText(items, (List<tClass>) imgval);
//            imgval=items;
//        }
//        else if (type.equals("2")){
//
//        }



        return null;
    }

    private String setAbsUrl(Object imgval,LbAbsFileUrl type) {
        if (type.type().equals("1")){
            if(oConvertUtils.isEmpty(imgval)) {
                return null;
            }
            return IpUtil.getImgStaticUrl(request, String.valueOf(imgval));
        }else if (type.type().equals("2")){
            if(oConvertUtils.isEmpty(imgval)) {
                return null;
            }
            StringBuffer textValue=new StringBuffer();
            String[] keys = String.valueOf(imgval).split(",");
            for (String k : keys) {
                String tmpValue = null;
                if (k.trim().length() == 0) {
                    continue; //跳过循环
                }
                tmpValue=IpUtil.getImgStaticUrl(request, k);
                if (tmpValue != null) {
                    if (!"".equals(textValue.toString())) {
                        textValue.append(",");
                    }
                    textValue.append(tmpValue);
                }
            }
            return textValue.toString();
        }
//        else if (type.type().equals("3")){
//
//        }
//        else if (type.equals("2")){
//
//        }



        return null;
    }

    private void setDictText(List<JSONObject> items, List records) {

        for (Object record : records) {
            ObjectMapper mapper = new ObjectMapper();
            String json="{}";
            try {
                //解决@JsonFormat注解解析不了的问题详见SysAnnouncement类的@JsonFormat
                 json = mapper.writeValueAsString(record);
            } catch (JsonProcessingException e) {
                log.error("json解析失败"+e.getMessage(),e);
            }
            JSONObject item = JSONObject.parseObject(json);
            //update-begin--Author:scott -- Date:20190603 ----for：解决继承实体字段无法翻译问题------
            //for (Field field : record.getClass().getDeclaredFields()) {
            for (Field field : oConvertUtils.getAllFields(record)) {
            //update-end--Author:scott  -- Date:20190603 ----for：解决继承实体字段无法翻译问题------
                if (field.getAnnotation(Dict.class) != null) {
                    String code = field.getAnnotation(Dict.class).dicCode();
                    String text = field.getAnnotation(Dict.class).dicText();
                    String table = field.getAnnotation(Dict.class).dictTable();
                    String key = String.valueOf(item.get(field.getName()));

                    //翻译字典值对应的txt
                    String textValue = translateDictValue(code, text, table, key);

                    log.debug(" 字典Val : "+ textValue);
                    log.debug(" __翻译字典字段__ "+field.getName() + CommonConstant.DICT_TEXT_SUFFIX+"： "+ textValue);
                    item.put(field.getName() + CommonConstant.DICT_TEXT_SUFFIX, textValue);
                }
                if (field.getAnnotation(LbAbsFileUrl.class) != null) {
                    LbAbsFileUrl type = field.getAnnotation(LbAbsFileUrl.class);
                    Object imgval = item.get(field.getName());
                    //翻译字典值对应的txt
                    String absurl = setAbsUrl(imgval,type);
                    item.put(field.getName() + "_absurl", absurl);
                }
                if (field.getAnnotation(LbImgBase64.class) != null) {
                    LbImgBase64 type = field.getAnnotation(LbImgBase64.class);
                    Object imgval = item.get(field.getName());
                    //翻译字典值对应的txt
                    String base64 = setBase64(imgval,type);
                    item.put(field.getName() + "_base64", base64);
                }
                //date类型默认转换string格式化日期
                if (field.getType().getName().equals("java.util.Date")&&field.getAnnotation(JsonFormat.class)==null&&item.get(field.getName())!=null){
                    SimpleDateFormat aDate=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                    item.put(field.getName(), aDate.format(new Date((Long) item.get(field.getName()))));
                }
            }
            items.add(item);
        }
    }

    /**
     *  翻译字典文本
     * @param code
     * @param text
     * @param table
     * @param key
     * @return
     */
    private String translateDictValue(String code, String text, String table, String key) {
        if(oConvertUtils.isEmpty(key)) {
            return null;
        }
        StringBuffer textValue=new StringBuffer();
        String[] keys = key.split(",");
        for (String k : keys) {
            String tmpValue = null;
            log.debug(" 字典 key : "+ k);
            if (k.trim().length() == 0) {
                continue; //跳过循环
            }
            if (!StringUtils.isEmpty(table)){
                log.debug("--DictAspect------dicTable="+ table+" ,dicText= "+text+" ,dicCode="+code);
                tmpValue= commonAPI.translateDictFromTable(table,text,code,k.trim());
            }else {
                tmpValue = commonAPI.translateDict(code, k.trim());
            }
            if (tmpValue != null) {
                if (!"".equals(textValue.toString())) {
                    textValue.append(",");
                }
                textValue.append(tmpValue);
            }

        }
        return textValue.toString();
    }

}
